All files / controllers WidgetController.js

0% Statements 0/174
0% Branches 0/76
0% Functions 0/9
0% Lines 0/174

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Widget Controller
 * 
 * Handles WhatsApp chat widget configuration and analytics for multi-tenant system.
 * Provides CRUD operations, embed code generation, and event tracking.
 * 
 * @module controllers/WidgetController
 */
 
const pool = require('../config/database').pool;
const { logger } = require('../config/logger');
const crypto = require('crypto');
 
class WidgetController {
  /**
   * Get all widgets for tenant
   * @route GET /api/widget/admin
   */
  static async getAllWidgets(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 10;
      const offset = (page - 1) * limit;
      const search = req.query.search || '';
 
      let query = `
        SELECT * FROM chat_widgets 
        WHERE tenant_id = ?
      `;
      const params = [tenantId];
 
      if (search) {
        query += ` AND (name LIKE ? OR whatsapp_number LIKE ? OR button_title LIKE ?)`;
        const searchPattern = `%${search}%`;
        params.push(searchPattern, searchPattern, searchPattern);
      }
 
      query += ` ORDER BY created_at DESC LIMIT ? OFFSET ?`;
      params.push(limit, offset);
 
      const [widgets] = await pool.execute(query, params);
 
      // Get total count
      let countQuery = `SELECT COUNT(*) as total FROM chat_widgets WHERE tenant_id = ?`;
      const countParams = [tenantId];
 
      if (search) {
        countQuery += ` AND (name LIKE ? OR whatsapp_number LIKE ? OR button_title LIKE ?)`;
        const searchPattern = `%${search}%`;
        countParams.push(searchPattern, searchPattern, searchPattern);
      }
 
      const [countResult] = await pool.execute(countQuery, countParams);
      const total = countResult[0].total;
 
      logger.info('Widgets retrieved', { 
        tenantId, 
        count: widgets.length,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        data: {
          data: widgets,
          pagination: {
            page,
            limit,
            total,
            totalPages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error) {
      logger.error('Error getting widgets', { 
        error: error.message,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve widgets'
      });
    }
  }
 
  /**
   * Get widget by ID
   * @route GET /api/widget/admin/:id
   */
  static async getWidgetById(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const widgetId = req.params.id;
 
      const [widgets] = await pool.execute(
        'SELECT * FROM chat_widgets WHERE id = ? AND tenant_id = ?',
        [widgetId, tenantId]
      );
 
      if (widgets.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found'
        });
      }
 
      logger.info('Widget retrieved', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        data: widgets[0]
      });
    } catch (error) {
      logger.error('Error getting widget', { 
        error: error.message,
        widgetId: req.params.id,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve widget'
      });
    }
  }
 
  /**
   * Create new widget
   * @route POST /api/widget/admin
   */
  static async createWidget(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const {
        name,
        whatsapp_number,
        button_title,
        button_background_color,
        widget_title,
        predefined_message,
        max_message_length,
        margin_right,
        margin_bottom,
        border_radius,
        is_active
      } = req.body;
 
      // Generate unique token
      const widget_token = crypto.randomBytes(32).toString('hex');
 
      const [result] = await pool.execute(
        `INSERT INTO chat_widgets (
          tenant_id, name, whatsapp_number, button_title, 
          button_background_color, widget_title, predefined_message,
          max_message_length, margin_right, margin_bottom, 
          border_radius, widget_token, is_active
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          tenantId, name, whatsapp_number, button_title,
          button_background_color || '#25D366', widget_title,
          predefined_message || null, max_message_length || 500,
          margin_right || 20, margin_bottom || 20,
          border_radius || 50, widget_token, is_active !== false
        ]
      );
 
      const widgetId = result.insertId;
 
      // Get created widget
      const [widgets] = await pool.execute(
        'SELECT * FROM chat_widgets WHERE id = ?',
        [widgetId]
      );
 
      logger.info('Widget created', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.status(201).json({
        success: true,
        message: 'Widget created successfully',
        data: widgets[0]
      });
    } catch (error) {
      logger.error('Error creating widget', { 
        error: error.message,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to create widget'
      });
    }
  }
 
  /**
   * Update widget
   * @route PUT /api/widget/admin/:id
   */
  static async updateWidget(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const widgetId = req.params.id;
 
      // Check if widget exists and belongs to tenant
      const [existing] = await pool.execute(
        'SELECT id FROM chat_widgets WHERE id = ? AND tenant_id = ?',
        [widgetId, tenantId]
      );
 
      if (existing.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found'
        });
      }
 
      const {
        name,
        whatsapp_number,
        button_title,
        button_background_color,
        widget_title,
        predefined_message,
        max_message_length,
        margin_right,
        margin_bottom,
        border_radius,
        is_active
      } = req.body;
 
      const updates = [];
      const values = [];
 
      if (name !== undefined) {
        updates.push('name = ?');
        values.push(name);
      }
      if (whatsapp_number !== undefined) {
        updates.push('whatsapp_number = ?');
        values.push(whatsapp_number);
      }
      if (button_title !== undefined) {
        updates.push('button_title = ?');
        values.push(button_title);
      }
      if (button_background_color !== undefined) {
        updates.push('button_background_color = ?');
        values.push(button_background_color);
      }
      if (widget_title !== undefined) {
        updates.push('widget_title = ?');
        values.push(widget_title);
      }
      if (predefined_message !== undefined) {
        updates.push('predefined_message = ?');
        values.push(predefined_message);
      }
      if (max_message_length !== undefined) {
        updates.push('max_message_length = ?');
        values.push(max_message_length);
      }
      if (margin_right !== undefined) {
        updates.push('margin_right = ?');
        values.push(margin_right);
      }
      if (margin_bottom !== undefined) {
        updates.push('margin_bottom = ?');
        values.push(margin_bottom);
      }
      if (border_radius !== undefined) {
        updates.push('border_radius = ?');
        values.push(border_radius);
      }
      if (is_active !== undefined) {
        updates.push('is_active = ?');
        values.push(is_active);
      }
 
      if (updates.length === 0) {
        return res.status(400).json({
          success: false,
          error: 'No fields to update'
        });
      }
 
      values.push(widgetId, tenantId);
 
      await pool.execute(
        `UPDATE chat_widgets SET ${updates.join(', ')} WHERE id = ? AND tenant_id = ?`,
        values
      );
 
      // Get updated widget
      const [widgets] = await pool.execute(
        'SELECT * FROM chat_widgets WHERE id = ?',
        [widgetId]
      );
 
      logger.info('Widget updated', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        message: 'Widget updated successfully',
        data: widgets[0]
      });
    } catch (error) {
      logger.error('Error updating widget', { 
        error: error.message,
        widgetId: req.params.id,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to update widget'
      });
    }
  }
 
  /**
   * Delete widget
   * @route DELETE /api/widget/admin/:id
   */
  static async deleteWidget(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const widgetId = req.params.id;
 
      const [result] = await pool.execute(
        'DELETE FROM chat_widgets WHERE id = ? AND tenant_id = ?',
        [widgetId, tenantId]
      );
 
      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found'
        });
      }
 
      logger.info('Widget deleted', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        message: 'Widget deleted successfully'
      });
    } catch (error) {
      logger.error('Error deleting widget', { 
        error: error.message,
        widgetId: req.params.id,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to delete widget'
      });
    }
  }
 
  /**
   * Generate embed code for widget
   * @route GET /api/widget/admin/:id/embed-code
   */
  static async generateEmbedCode(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const widgetId = req.params.id;
 
      const [widgets] = await pool.execute(
        'SELECT id, widget_token FROM chat_widgets WHERE id = ? AND tenant_id = ?',
        [widgetId, tenantId]
      );
 
      if (widgets.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found'
        });
      }
 
      const widget = widgets[0];
      const baseUrl = process.env.APP_URL || 'http://localhost:7000';
 
      const embedCode = `<script>
  (function() {
    var script = document.createElement('script');
    script.src = '${baseUrl}/widget/embed.js';
    script.setAttribute('data-widget-id', '${widget.id}');
    script.setAttribute('data-widget-token', '${widget.widget_token}');
    script.async = true;
    document.head.appendChild(script);
  })();
</script>`;
 
      logger.info('Embed code generated', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        data: {
          embedCode,
          widgetId: widget.id,
          widgetToken: widget.widget_token
        }
      });
    } catch (error) {
      logger.error('Error generating embed code', { 
        error: error.message,
        widgetId: req.params.id,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to generate embed code'
      });
    }
  }
 
  /**
   * Get widget analytics
   * @route GET /api/widget/admin/:id/analytics
   */
  static async getWidgetAnalytics(req, res) {
    try {
      const tenantId = req.user.tenantId;
      const widgetId = req.params.id;
      const startDate = req.query.start_date;
      const endDate = req.query.end_date;
 
      // Verify widget belongs to tenant
      const [widgets] = await pool.execute(
        'SELECT id FROM chat_widgets WHERE id = ? AND tenant_id = ?',
        [widgetId, tenantId]
      );
 
      if (widgets.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found'
        });
      }
 
      let query = `
        SELECT 
          event_type,
          COUNT(*) as count,
          DATE(created_at) as date
        FROM widget_analytics
        WHERE widget_id = ? AND tenant_id = ?
      `;
      const params = [widgetId, tenantId];
 
      if (startDate) {
        query += ` AND created_at >= ?`;
        params.push(startDate);
      }
      if (endDate) {
        query += ` AND created_at <= ?`;
        params.push(endDate + ' 23:59:59');
      }
 
      query += ` GROUP BY event_type, DATE(created_at) ORDER BY date DESC`;
 
      const [analytics] = await pool.execute(query, params);
 
      // Get summary
      const [summary] = await pool.execute(
        `SELECT 
          event_type,
          COUNT(*) as total
        FROM widget_analytics
        WHERE widget_id = ? AND tenant_id = ?
        GROUP BY event_type`,
        [widgetId, tenantId]
      );
 
      logger.info('Widget analytics retrieved', { 
        widgetId, 
        tenantId,
        userId: req.user.id 
      });
 
      res.json({
        success: true,
        data: {
          analytics,
          summary
        }
      });
    } catch (error) {
      logger.error('Error getting widget analytics', { 
        error: error.message,
        widgetId: req.params.id,
        tenantId: req.user?.tenantId,
        userId: req.user?.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve analytics'
      });
    }
  }
 
  /**
   * Get widget by token (public)
   * @route GET /api/widget/public/:id/:token
   */
  static async getWidgetByToken(req, res) {
    try {
      const widgetId = req.params.id;
      const token = req.params.token;
 
      const [widgets] = await pool.execute(
        `SELECT 
          id, name, whatsapp_number, button_title, button_background_color,
          widget_title, predefined_message, max_message_length,
          margin_right, margin_bottom, border_radius
        FROM chat_widgets 
        WHERE id = ? AND widget_token = ? AND is_active = TRUE`,
        [widgetId, token]
      );
 
      if (widgets.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found or inactive'
        });
      }
 
      res.json({
        success: true,
        data: widgets[0]
      });
    } catch (error) {
      logger.error('Error getting widget by token', { 
        error: error.message,
        widgetId: req.params.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve widget'
      });
    }
  }
 
  /**
   * Track widget event (public)
   * @route POST /api/widget/public/:id/:token/track
   */
  static async trackWidgetEvent(req, res) {
    try {
      const widgetId = req.params.id;
      const token = req.params.token;
      const { event_type, event_data } = req.body;
 
      // Verify widget exists and is active
      const [widgets] = await pool.execute(
        'SELECT id, tenant_id FROM chat_widgets WHERE id = ? AND widget_token = ? AND is_active = TRUE',
        [widgetId, token]
      );
 
      if (widgets.length === 0) {
        return res.status(404).json({
          success: false,
          error: 'Widget not found or inactive'
        });
      }
 
      const widget = widgets[0];
 
      // Get client info
      const ipAddress = req.ip || req.connection.remoteAddress;
      const userAgent = req.headers['user-agent'];
      const referrer = req.headers['referer'] || req.headers['referrer'];
      const sessionId = req.body.session_id || crypto.randomBytes(16).toString('hex');
 
      await pool.execute(
        `INSERT INTO widget_analytics (
          tenant_id, widget_id, event_type, event_data,
          ip_address, user_agent, referrer_url, page_url, session_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          widget.tenant_id, widgetId, event_type,
          event_data ? JSON.stringify(event_data) : null,
          ipAddress, userAgent, referrer,
          event_data?.page_url || null, sessionId
        ]
      );
 
      res.json({
        success: true,
        message: 'Event tracked successfully'
      });
    } catch (error) {
      logger.error('Error tracking widget event', { 
        error: error.message,
        widgetId: req.params.id 
      });
      res.status(500).json({
        success: false,
        error: 'Failed to track event'
      });
    }
  }
}
 
module.exports = WidgetController;